// 添加必要的导入语句
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');

// 导出函数，让外部可以传入必要的参数
module.exports = function(VIDEOS_DIR, IMAGES_DIR) {
  // Ensure directories exist
  const ensureDirectories = () => {
    if (!fs.existsSync(VIDEOS_DIR)) {
      fs.mkdirSync(VIDEOS_DIR, { recursive: true });
    }
    if (!fs.existsSync(IMAGES_DIR)) {
      fs.mkdirSync(IMAGES_DIR, { recursive: true });
    }
  };

  // Extract first frame from video using ffmpeg
  const extractFirstFrame = (videoPath, imagePath) => {
    return new Promise((resolve, reject) => {
      const ffmpeg = spawn('ffmpeg', [
        '-i', videoPath,
        '-vframes', '1',
        '-q:v', '2',
        imagePath
      ]);

      ffmpeg.on('close', (code) => {
        if (code === 0) {
          resolve(imagePath);
        } else {
          reject(new Error(`FFmpeg process exited with code ${code}`));
        }
      });

      ffmpeg.on('error', (err) => {
        reject(err);
      });
    });
  };

  // Process new video file
  const processVideoFile = async (filePath) => {
    const filename = path.basename(filePath, '.mp4');
    const imagePath = path.join(IMAGES_DIR, `${filename}.jpg`);

    try {
      // Check if the target image file already exists
      if (fs.existsSync(imagePath)) {
        console.log(`Thumbnail already exists for ${filePath}, skipping frame extraction`);
      } else {
        // Extract first frame if image doesn't exist
        try {
          await extractFirstFrame(filePath, imagePath);
          console.log(`Extracted frame from ${filePath} to ${imagePath}`);
        } catch (ffmpegError) {
          console.error(`Failed to extract frame from ${filePath}:`, ffmpegError.message);
          // Use placeholder image when frame extraction fails
          const placeholderPath = path.join(__dirname, 'placeholder.jpg');
          try {
            // Copy placeholder to the expected image path
            fs.copyFileSync(placeholderPath, imagePath);
            console.log(`Used placeholder image for ${filePath}`);
          } catch (copyError) {
            console.error(`Failed to copy placeholder image for ${filePath}:`, copyError.message);
          }
        }
      }
    } catch (error) {
      console.error(`Error processing ${filePath}:`, error);
    }
  };

  // Monitor directory for new files
  const monitorDirectory = () => {
    console.log(`Monitoring directory: ${VIDEOS_DIR}`);
    
    // Process existing files on startup
    fs.readdir(VIDEOS_DIR, (err, files) => {
      if (err) {
        console.error('Error reading videos directory:', err);
        return;
      }
      
      files.filter(file => file.endsWith('.mp4')).forEach(file => {
        const filePath = path.join(VIDEOS_DIR, file);
        processVideoFile(filePath);
      });
    });

    // Watch for new files
    fs.watch(VIDEOS_DIR, (eventType, filename) => {
      if (eventType === 'rename' && filename.endsWith('.mp4')) {
        const filePath = path.join(VIDEOS_DIR, filename);
        
        // Wait a moment for file to be fully written
        setTimeout(() => {
          if (fs.existsSync(filePath)) {
            processVideoFile(filePath);
          }
        }, 1000);
      }
    });
  };

  // Initialize directories and return the monitor function
  ensureDirectories();
  return monitorDirectory;
};